import { useEffect } from "react";
import { Navigate, useSearchParams } from "react-router-dom";
import { message } from "antd";
import { useUserToken } from "@/store/userStore";
import { useWechatLogin } from "@/hooks/useWechatLogin";
import { WECHAT_CONFIG } from "@/config/wechat";

const { VITE_APP_HOMEPAGE: HOMEPAGE } = import.meta.env;

function WechatAuth() {
	const [searchParams] = useSearchParams();
	const { token } = useUserToken();
	const { login, isLoading } = useWechatLogin();

	useEffect(() => {
		const code = searchParams.get("code");
		const state = searchParams.get("state");

		if (!token && code) {
			// 有 code 说明是从微信授权页面跳转回来的
			login({ code, state }).catch((error) => {
				console.error("微信登录失败:", error);
				message.error("微信登录失败，请重试");
			});
		}
	}, [searchParams, token]);

	// 如果已经有 token，直接跳转到首页
	if (token) {
		return <Navigate to={HOMEPAGE} replace />;
	}

	// 如果没有 code，重定向到微信授权页面
	if (!searchParams.get("code") && !isLoading) {
		const { appId, redirectUri, scope } = WECHAT_CONFIG;
		const state = "STATE"; // 可以根据需要生成随机值

		const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(
			redirectUri,
		)}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;

		console.log("Redirecting to:", authUrl);
		window.location.replace(authUrl);
		return null;
	}

	// 正在登录中，显示加载状态
	return (
		<div className="flex h-screen w-full items-center justify-center">
			<div className="text-lg">登录中...</div>
		</div>
	);
}

export default WechatAuth;
